<?php

namespace App\Http\Controllers;

use App\Enum\UserType;
use App\Helper\ApiResponseHelper;
use App\Helper\SmsCode;
use App\Http\Requests\Counter\MemberPasswordRequest;
use App\Http\Requests\CRM\MemberRequest;
use App\Http\Resources\MemberResource;
use App\Models\Member;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MemberController extends Controller
{
    public function info(Member $member)
    {
        return new MemberResource($member);
    }

    public function search(Request $request)
    {
        //模糊查询
        $members = Member::where('phone', 'like', '%' . $request->phone . '%')->latest('phone')->get();

        return MemberResource::collection($members);
    }

    public function create(MemberRequest $request, SmsCode $smsCode)
    {
        $name = $request->input('name') ?? $request->input('phone');
        $code = $request->code;

        if (!$smsCode->verify($request->phone, $code))
            return ApiResponseHelper::json([], 400, '验证码错误');

        $smsCode->verifyAndClean($request->phone, $code);
        try {
            $member = Member::create(array_merge([
                'name' => $name,
                'member_level' => 'D',
                'member_month_level' => 'blue_v'
            ], $request->only(['phone', 'sex', 'password'])));

            return new MemberResource($member);
        } catch (\Exception $exception) {

            return ApiResponseHelper::json([], 400, '手机号已存在');
        }
    }

    public function changePassword(Member $member, MemberPasswordRequest $request, SmsCode $smsCode)
    {
        if (!$smsCode->verify($member->phone, $request->code))
            return ApiResponseHelper::json([], 400, '验证码错误');

        $smsCode->verifyAndClean($member->phone, $request->code);
        $member->password = $request->password;
        $member->save();

        return new MemberResource($member);
    }
}
